<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <template v-slot:header
          ><span>{{ title }}</span></template
        >
        <el-form label-width="120px" :model="form" :rules="rules" ref="form">
          <el-form-item label="学科：" prop="subjectID">
            <el-select
              v-model="form.subjectID"
              placeholder="请选择"
              style="width: 400px"
              @change="subjectChange"
            >
              <el-option
                v-for="item in subjectList"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录：" prop="catalogID">
            <el-select
              v-model="form.catalogID"
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option
                v-for="item in catalogList"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select
              v-model="form.enterpriseID"
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option
                v-for="item in companyList"
                :key="item.id"
                :value="item.id"
                :label="item.company"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市：" prop="city">
            <el-select
              v-model="form.province"
              placeholder="请选择"
              style="width: 200px"
              @change="ProvinceChange"
            >
              <el-option
                v-for="(item, i) of provincesList"
                :key="i"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <el-select
              v-model="form.city"
              placeholder="请选择"
              style="width: 200px"
            >
              <el-option
                v-for="(item, i) of citysList"
                :key="i"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方向：" prop="direction">
            <el-select
              v-model="form.direction"
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option
                v-for="(item, i) in directionList"
                :key="i"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型：">
            <el-radio-group
              v-model="form.questionType"
              @change="questionTypeChange"
            >
              <el-radio
                v-for="item in questionType"
                :key="item.value"
                :label="item.value"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度：">
            <el-radio-group v-model="form.difficulty">
              <el-radio
                v-for="item in difficulty"
                :key="item.value"
                :label="item.value"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="题干：" prop="question">
            <div>
              <quill-editor
                ref="myLQuillEditor"
                v-model="form.question"
                style="height: 254px;"
              >
              </quill-editor>
            </div>
          </el-form-item>
          <el-form-item label="选项：" v-if="!(form.questionType === '3')">
            <!-- <el-radio-group
              class="options"
              v-model="optionsCode"
              @change="optionsChange"
              v-if="form.questionType === '1'"
            >
              <el-radio
                class="optionsRadio"
                v-for="(item, i) in form.options"
                :key="i"
                :label="item.code"
              >
                {{ item.code }}：<el-input
                  v-model="item.title"
                  style="width: 240px"
                ></el-input
                ><imageUpload ref="imageUpload"></imageUpload
              ></el-radio>
            </el-radio-group> -->
            <div v-if="form.questionType === '1'">
              <div
                v-for="(item, i) in form.options"
                :key="i"
                class="checkboxDIV"
              >
                <el-radio
                  @input="optionsChange"
                  v-model="number"
                  :label="item.code"
                  >{{ item.code }}：</el-radio
                >
                <el-input v-model="item.title" style="width: 240px" />
                <imageUpload ref="imageUpload"></imageUpload>
              </div>
            </div>
            <div v-if="form.questionType === '2'">
              <!-- <el-checkbox-group class="options" v-model="checkCodeList" @change="optionsChange" v-if="form.questionType==='2'">
                <el-checkbox  class="optionsRadio" v-for="(item,i) in form.options" :key="i" :label="item.code" > {{item.code}}：<el-input v-model="item.title" style="width:240px"></el-input><imageUpload ref="imageUpload"></imageUpload>
								</el-checkbox>
							</el-checkbox-group> -->
              <div
                v-for="(item, i) in form.options"
                :key="i"
                class="checkboxDIV"
              >
                <el-checkbox v-model="item.isRight"
                  >{{ item.code }}：</el-checkbox
                >
                <el-input v-model="item.title" style="width: 240px" />
                <imageUpload ref="imageUpload"></imageUpload>
                <i
                  class="el-icon-circle-close delCheckbox"
                  @click="delCheckbox(item.code)"
                ></i>
              </div>
            </div>
            <el-button
              type="danger"
              :disabled="form.questionType === '1'"
              @click="addCheckbox"
              >增加选项与答案</el-button
            >
          </el-form-item>
          <el-form-item label="解析视频：">
            <el-input style="width: 400px" v-model="form.videoURL"></el-input>
          </el-form-item>
          <el-form-item label="答案解析：" prop="answer">
            <div class="local-quill-editor">
              <quill-editor
                ref="myLQuillEditor"
                v-model="form.answer"
                style="height: 254px"
              >
              </quill-editor>
            </div>
          </el-form-item>
          <el-form-item label="题目备注：">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="form.remarks"
              style="width: 400px"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="试题标签：">
            <el-select
              v-model="form.tags"
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option
                v-for="item in tagsList"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitBtn">确认提交</el-button>
          </el-form-item>
        </el-form>
      </el-card>
			<drag></drag>
    </div>
  </div>
</template>

<script>
import { simple as subjectApi } from '@/api/hmmm/subjects'
import { simple as catalogApi } from '@/api/hmmm/directorys'
import { list as companyListApi } from '@/api/hmmm/companys'
import { provinces as provincesApi, citys as citysApi } from '@/api/hmmm/citys'
import {
  direction as directionList,
  difficulty,
  questionType
} from '@/api/hmmm/constants'
import { simple as tagsApi } from '@/api/hmmm/tags'
import imageUpload from '@/components/imageUpload'
import {
  add as addApi,
  detail as detailApi,
  update as updateApi
} from '@/api/hmmm/questions'

export default {
  components: { imageUpload },
  computed: {
    editId () {
      return this.$route.query.id || ''
    },
    path () {
      return this.$route.query.path || ''
    },
    title () {
      return this.form.id ? '试题修改' : '试题录入'
    }
  },
  data () {
    return {
      form: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: ''
      },
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ],
        city: [{ required: true, message: '请选择地区', trigger: 'blur' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' }
        ]
      },
      subjectList: [],
      catalogList: [],
      companyList: [],
      provincesList: [],
      citysList: [],
      directionList,
      tagsList: [],
      difficulty,
      questionType,
      optionsCode: '',
      checkCodeList: [],
      number: '',
      editForm: {}
    }
  },
  created () {
    this.getsubjectList()
    this.getcompanyList()
    this.getProvinces()
    this.detail()
    // this.cleardata()
  },
  methods: {
    /**
     *基础题库修改数据回显
     */
    async detail () {
      if (!this.editId) return
      const { data } = await detailApi({ id: this.editId })
      console.log(data)
      let arr = []

      data.options.forEach((item, i) => {
        // 选项得回显
        item.isRight = !!item.isRight
        if (item.isRight) {
          this.number = item.code
        }
        arr.push(item.code.charCodeAt())
      })
      // 选项排序
      arr.sort(function (a, b) { return a - b })
      arr = arr.map(item => String.fromCharCode(item))
      const res = []
      arr.forEach((item, i) => {
        data.options.forEach((k) => {
          if (item === k.code) {
            res.push(k)
          }
        })
      })
      data.options = res
      data.options.forEach((item, i) => {
        // 图片得回显
        this.$nextTick(() => {
          if (item.img) {
            const imageUpload = this.$refs.imageUpload
            imageUpload[i].fileList.push({ url: item.img })
          }
        })
      })
      this.form = data
      this.getcatalogList()
      this.getTagsList()
    },
    /**
     * form表单提交处理(添加照片)
     */
    submitBtn () {
      this.$refs.form.validate(async (flag) => {
        if (!flag) return
        this.form.options.forEach(async (item, i) => {
          await this.$nextTick()
          const imageUpload = this.$refs.imageUpload
          item.img = imageUpload[i]?.fileList[0]?.url || ''
        })
        this.$nextTick(async () => {
          if (this.form.id) {
            await updateApi(this.form)
            this.$message.success('修改成功')
          } else {
            await addApi(this.form)
            this.$message.success('新增成功')
          }
          this.cleardata()
          if (this.path === '2') {
            this.$router.push('/questions/choice')
          } else {
            this.$router.push('/questions/list')
          }
        })
      })
    },
    /**
		 * 数据清空
		 */
    cleardata () {
      this.$refs.form.resetFields()
      this.form = {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: ''
      }
      const imageUpload = this.$refs.imageUpload
      imageUpload.forEach((item) => {
        item.fileList[0] = {}
      })
    },
    /**
     * 多选得选项删除方法
     */
    delCheckbox (val) {
      const index = this.form.options.findIndex((item) => item.code === val)
      this.form.options.splice(index, 1)
      // 删除后 后续选项依次提前
      let a = val.charCodeAt() - 1
      this.form.options.forEach((item, i) => {
        if (i >= index) {
          a++
          item.code = String.fromCharCode(a)
        }
      })
    },
    /**
     * 多选新增选项和答案
     */
    addCheckbox () {
      // 通过ascii码自动新增选项字母
      const a = this.form.options[this.form.options.length - 1].code
      const b = String.fromCharCode(a.charCodeAt() + 1)
      const obj = { isRight: false, code: b, title: '', img: '' }
      this.form.options.push(obj)
    },
    /**
     * 题型变化时执行初始化选项数据
     */
    questionTypeChange () {
      this.number = ''
      this.form.options = [
        { isRight: false, code: 'A', title: '', img: '' },
        { isRight: false, code: 'B', title: '', img: '' },
        { isRight: false, code: 'C', title: '', img: '' },
        { isRight: false, code: 'D', title: '', img: '' }
      ]
    },
    /**
     * 选择题得选项触发得函数
     */
    optionsChange (val) {
      this.form.options.forEach((item) => {
        if (item.code === val) {
          this.form.options.forEach((key) => {
            key.isRight = false
          })
          item.isRight = true
        }
      })
      //  else if (this.form.questionType === '2') {
      //   this.form.options.forEach((item) => {
      //     if (val.includes(item.code)) {
      //       item.isRight = true
      //     }
      //   })
      // }
    },
    /**
     * 	获取标签列表信息
     */
    async getTagsList () {
      const { data } = await tagsApi({ page: 1, pagesize: 999, subjectID: this.form.subjectID })
      // this.form.tags = ''
      data.forEach(item => {
        item.value = item.value.toString()
      })
      this.tagsList = data
      console.log(this.tagsList)
    },
    ProvinceChange () {
      this.getCitysList()
    },
    /**
     * 获取城市列表信息
     */
    getCitysList () {
      const res = citysApi(this.form.province)
      this.form.city = ''
      this.citysList = res
    },
    /**
     * 获取省份列表信息
     */
    getProvinces () {
      const res = provincesApi()
      this.provincesList = res
    },
    /**
     * 获取公司列表信息
     */
    async getcompanyList () {
      const {
        data: { items }
      } = await companyListApi({ page: 1, pagesize: 1000 })
      this.companyList = items
    },
    subjectChange () {
      this.getcatalogList()
      this.getTagsList()
    },
    /**
     * 获取学科列表信息
     */
    async getsubjectList () {
      const { data } = await subjectApi()
      this.subjectList = data
    },
    /**
     * 获取目录列表信息
     */
    async getcatalogList () {
      const { data } = await catalogApi({ page: 1, pagesize: 999, subjectID: this.form.subjectID })
      // this.form.catalogID = ''
      this.catalogList = data
    }
  }
}
</script>

<style scoped lang="scss">
.el-form {
  ::v-deep {
    .ql-container.ql-snow {
      height: 200px;
    }
    .checkboxDIV {
      position: relative;
      display: block;
      margin-bottom: 20px;
      height: 80px;
      width: 100%;
    }
    .checkboxDIV .el-radio {
      margin-right: 0;
    }
    .image-upload {
      position: absolute;
      // right: -90px;
      left: 295px;
      top: -12px;
      width: 100px;
      height: 60px;
    }
    .image-upload .el-icon-plus {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
    .el-upload--picture-card,
    .el-upload-list__item {
      width: 100px;
      height: 60px;
    }
    .el-icon-circle-close.delCheckbox {
      position: absolute;
      left: 380px;
      top: -24px;
      font-size: 25px;
      color: #555;
    }
		.ql-toolbar.ql-snow{
			height: 50px;
			overflow:auto;
		}
  }
}
</style>
